import unittest
import os
import time
from BeautifulReport import BeautifulReport

# 定义各目录
ProjectHome = os.path.split(os.path.realpath(__file__))[0]
PageObjectPath = os.path.join(ProjectHome, "Page")
TestCasePath = os.path.join(ProjectHome, "Testcase")
ReportPath = os.path.join(ProjectHome, "Report")


# 加载测试用例
def get_suite(case_path=TestCasePath, rule="test_*.py"):
    """加载所有的测试用例"""
    unittest_suite = unittest.TestSuite()
    discover = unittest.defaultTestLoader.discover(case_path, pattern=rule, top_level_dir=None)
    for each in discover:
        unittest_suite.addTests(each)
    return unittest_suite

# 执行用例，生成测试报告，并返回报告附件路径、邮件正文内容
def suite_run(unittest_suite):
    """执行所有的用例, 并把结果写入测试报告"""
    run_result = BeautifulReport(unittest_suite)
    now = time.strftime("%Y-%m-%d+%H_%M_%S", time.localtime())
    filename = now + '_report.html'
    run_result.report(filename=filename, description=now, log_path=ReportPath)
    return os.path.join(ReportPath, filename)

# 主程序，加载用例，执行用例
if __name__ == "__main__":
    suite = get_suite()
    report_file = suite_run(suite)
